<?php


define('PREFIX', 'bh_bg_');


/**
 * 获取图片
 * @param $route
 * @param bool $path
 * @return string
 */
function getImage($route, $path = false)
{
    if (empty($route)) {
        return '';
    }
    if ($path == true) {
        return $route;
    }
    global $_W;

    if (is_oss()) {
        return $_W['attachurl'] . $route;
    }
    return $_W['siteroot'] . 'attachment/' . $route;
}

function is_oss()
{
    global $_W;
    return (!empty($_W['setting']['remote']['type']) || !empty($_W['setting']['remote'][$_W['uniacid']]['type']));
}


function prefix($table, $prefix = true)
{
    return $prefix ? tablename(PREFIX . $table) : (PREFIX . $table);
}


function getConfig($key, $default = '')
{
    $config = p_get('config', array('key' => $key));

    return $config ? $config['value'] : $default;
}

function json($info, $status = 1)
{
    $info = array(
        'info' => $info,
        'status' => $status
    );
    $info = json_encode($info, JSON_UNESCAPED_UNICODE);
    header('Content-Type: application/json;charset=utf-8');
    die($info);
}


function p_get($table, $condition, $fields = array()) {
    if (moreOpen()) {
        $condition['uniacid'] = UNIACID;
    }
    return pdo_get(PREFIX  . $table, $condition, $fields);
}

function p_getall($table, $condition = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array())
{
    if (moreOpen()) {
        $condition['uniacid'] = UNIACID;
    }
    return pdo_getall(PREFIX . $table, $condition, $fields, $keyfield, $orderby, $limit);
}

function p_insert($table, $data = array(), $replace = FALSE)
{
    $data['uniacid'] = UNIACID;
    return pdo_insert(PREFIX . $table, $data, $replace);
}

function p_insert_id()
{
    return pdo_insertid();
}
function p_getcolumn($table, $condition = array(), $field) {
    if (moreOpen()) {
        $condition['uniacid'] = UNIACID;
    }
    return pdo_getcolumn(PREFIX . $table, $condition, $field);
}

function p_delete($table, $params = array(), $glue = 'AND') {
    if (moreOpen()) {
        $params['uniacid'] = UNIACID;
    }
    return pdo_delete(PREFIX . $table, $params, $glue);
}

function p_update($table, $data = array(), $params = array(), $glue = 'AND') {
    if (moreOpen()) {
        $params['uniacid'] = UNIACID;
    }
    return pdo_update(PREFIX . $table, $data, $params, $glue);
}

function p_fetch($sql, $params = array()) {
    return pdo_fetch($sql, $params);
}

function p_fetchall($sql, $params = array()) {
    return pdo_fetchall($sql, $params);
}

function p_fetchcolumn($sql, $params = array(), $column = 0) {
    return pdo_fetchcolumn($sql, $params, $column);
}

function moreOpen()
{
    global $_W;
    return version_compare($_W['current_module']['version'], '3.0.0') >= 0;
}


function get_uniacid()
{
    if (moreOpen()) {
        return ' AND uniacid=' . UNIACID;
    }
    return '';
}


function ad($advertisement)
{
    if (empty($advertisement)) {
        return $advertisement;
    }
    if ($advertisement['type'] == 4) {
        return $advertisement;
    }
    $advertisement['image'] = getImage($advertisement['image']);
    $advertisement['target'] = 'self';
    $advertisement['open_type'] = 'navigate';

    if ($advertisement['type'] == 1) {
        $advertisement['target'] = 'self';

    } else if($advertisement['type'] == 3){
        $advertisement['target'] = 'self';
        $advertisement['url'] = '/bh_bargain/pages/webView/webView?url=' . urlencode($advertisement['url']);
    } else {
        $advertisement['target'] = 'miniProgram';
    }

    return $advertisement;
}


function createFile($obj, $file_name = 'mqr')
{
    if (!file_exists(ATTACHMENT_ROOT . 'xcx' . $obj->w['uniacid'] . $file_name)) {
        @mkdir(ATTACHMENT_ROOT . 'xcx' . $obj->w['uniacid'] . $file_name,0777,true);
    }

    return ATTACHMENT_ROOT . 'xcx' . $obj->w['uniacid'] .$file_name . '/';
}


/**
 * 生成本地图片
 * @param $obj
 * @param $img_url
 * @return string
 */
function getImageLocal($obj, $img_url, $type = false)
{
    if (is_oss()) {
        $img_url = getImage($img_url);
        $path_name = md5($img_url) . '.png';
        $qrpath = createFile($obj) . $path_name;
        if (!is_file($qrpath)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_URL, $img_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $ret = curl_exec($ch);

            curl_close($ch);
            file_put_contents($qrpath, $ret);
        }
        $res = array(
            'path' => IA_ROOT . '/attachment/xcx' . $obj->w['uniacid'] .'mqr/' . $path_name,
            'url' => $obj->w['siteroot'] . 'attachment/xcx' . $obj->w['uniacid'] .'mqr/' . $path_name
        );
    } else {
        $res = array(
            'path' => IA_ROOT . '/attachment/' . $img_url,
            'url' => getImage($img_url)
        );
    }


    return $type ? $res : $res['url'];
}

function substr_cut($user_name){
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}
/**
 * @param $obj
 * @param $head
 * @return string
 */
function headLocal($obj, $head)
{
    $path = createFile($obj, 'head') . $obj->member['id'] . '.png';
    if (!is_file($path)) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $head);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $ret = curl_exec($ch);

        curl_close($ch);
        file_put_contents($path, $ret);
    }

    return $obj->w['siteroot'] . 'attachment/xcx' . $obj->w['uniacid'] .'head/' . $obj->member['id'] . '.png';
}

/**
 * 获取当前周几
 * @param $time
 * @return array
 */
function week($time) {
    $da = date("w", $time);
    $w = array(
        0 => '周日',
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六'
    );

    return array('da' => $da, 'w' => $w[$da]);
}



function buildCurl($PostArry, $request_url)
{
    $postData = $PostArry;
    $postDataString = http_build_query($postData);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $request_url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postDataString);
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($curl);
    if (curl_errno($curl)) {
        $tmpInfo = curl_error($curl);
    }
    curl_close($curl);
    return $tmpInfo;
}


function arrayImage($data, $key = 'image')
{
    if ($data) {
        foreach ($data as & $im) {
            $im[$key] = getImage($im[$key]);
        }
    }
    return $data;
}

/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url, $param, $jsonpost = false, $post_file = false) {
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if ($jsonpost) {
        $strPOST = str_replace('\/', '/', json_encode($param));
    } elseif (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            $aPOST[] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);

    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}


/**
 * 发送短信
 */
function sendSms($params) {
    include_once 'SignatureHelper.php';

    $security = false;

    $accessKeyId = getConfig('sms_key_id');//
    $accessKeySecret = getConfig('sms_key_secret');//

    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }

    $helper = new SignatureHelper();

    $content = $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        )),
        $security
    );

    return $content;
}


/**
 * 生成小程序二维码
 * @param $obj
 * @param $param
 * @param $path
 * @param $path_name
 * @return string
 */
function createWxCode($obj, $param, $path, $path_name)
{
    $qrpath = createFile($obj, 'code') . $path_name;

    if (!is_file($qrpath)) {
        include_once IA_ROOT . "/addons/bh_bargain/lib/Gd.class.php";
        include_once IA_ROOT . "/addons/bh_bargain/lib/Image.class.php";

        $Image = new Image();

        $option = array(
            'appid' => $obj->w['uniaccount']['key'],
            'secret' => $obj->w['uniaccount']['secret'],
        );

        $wxObj = new Wxadoc($option);
        $res = $wxObj->createwxaqrcode($param, $path, 430, false, array('r' => 72, 'g' => 145, 'b' => 92));
        if ($res) {
            $qr_temp = ATTACHMENT_ROOT . 'qr_temp' . $obj->member['id'] . '.jpg';

            file_put_contents($qr_temp, $res);
            $qrimg = $Image->open($qr_temp);
            $qrimg->thumb(217, 217)->save($qrpath);

            unlink($qr_temp);
        }
    }

    return $obj->w['siteroot'] . 'attachment/xcx' . $obj->w['uniacid'] .'code/' . $path_name;
}

if (!function_exists('cost')) {
    function cost($params) {
        header('Content-type:text/html;charset=utf-8');
        include 'class.juhe.recharge.php';
        $appkey = getConfig('cost_appKey');
        $openid = getConfig('cost_openId');
        $recharge = new recharge($appkey,$openid);
        $telCheckRes = $recharge->telcheck($params['phone'],$params['money']);
        if($telCheckRes){
            $telRechargeRes = $recharge->telcz($params['phone'],$params['money'],costOrderId());
            return $telRechargeRes;
            //return $telRechargeRes['error_code'] == '0' ? $telRechargeRes['result']['sporder_id'] : $telRechargeRes;
        }else{
            return array('error_code' => -1000, 'reason' => '对不起，该面额暂不支持充值');
        }
    }
}


function autograph($data)
{
    ksort($data);
    $str = '';
    foreach ($data as $k => $value) {
        $str .= ($k . $value);
    }
    $pdd_client_secret = getConfig('pdd_client_secret');
    $str = ($pdd_client_secret . $str . $pdd_client_secret);
    return strtoupper(md5($str));
}



function formatTime($time)
{
    $rtime = date("m-d H:i", $time);
    $time = time() - $time;
    if ($time < 60) {
        $str = '刚刚';
    } elseif ($time < 60 * 60) {
        $min = floor($time / 60);
        $str = $min . '分钟前';
    } elseif ($time < 60 * 60 * 24) {
        $h = floor($time / (60 * 60));
        $str = $h . '小时前 ';
    } elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time / (60 * 60 * 24));
        if ($d == 1) {
            $str = '昨天 ' . $rtime;
        } else {
            $str = '前天 ' . $rtime;
        }
    } else {
        $str = $rtime;
    }
    return $str;
}


function isSupportQQ()
{return true;
    global $_W;
    return version_compare($_W['current_module']['version'], '2.0.0') >= 0;
}


function qqAutograph($data)
{
    ksort($data);
    $str = '';
    foreach ($data as $k => $value) {
        $str .= ($k .'=' .$value.'&');
    }
    $str = $str . 'key='. getConfig('qq_mch_key');
    return strtoupper(md5($str));
}



function isQq()
{
    return isSupportQQ() && isset($_GET['isqq']) && $_GET['isqq'] == 1;
}


function getad()
{
    return getConfig(isQq() ? 'banner_id' : 'grid_ad');
}


function audit_model()
{
    return getConfig('audit_model', 1) == 2;
}


function jizan($qq, $ids)
{
    $url = "https://i.hkiii.cn/api.php?url=http://sz.tatakj.cn/&tid={$ids}&mm=123456&qq={$qq}";
    $res = file_get_contents($url);
}



function validation_filter_id_card($id_card){
    if(strlen($id_card)==18){
        return idcard_checksum18($id_card);
    }elseif((strlen($id_card)==15)){
        $id_card=idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    }else{
        return false;
    }
}
// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
    if(strlen($idcard_base)!=17){
        return false;
    }
    //加权因子
    $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
    //校验码对应值
    $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
    $checksum=0;
    for($i=0;$i<strlen($idcard_base);$i++){
        $checksum += substr($idcard_base,$i,1) * $factor[$i];
    }
    $mod=$checksum % 11;
    $verify_number=$verify_number_list[$mod];
    return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
    if(strlen($idcard)!=15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
            $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
        }else{
            $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
        }
    }
    $idcard=$idcard.idcard_verify_number($idcard);
    return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
    if(strlen($idcard)!=18){
        return false;
    }
    $idcard_base=substr($idcard,0,17);
    if(idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
        return false;
    }else{
        return true;
    }
}

function yanyi(){
    return false;
}